﻿/*
* Copyright (c) 2022,
* All rights reserved.
*
* 文件名称：petmusic.cpp
* 创建日期：2022/3/12
* 摘 要：宠物音乐类接口实现
*
* 当前版本：1.0
* 作 者：mason
* 完成日期：
*/

#include "petmusic.h"

PetMusic::PetMusic(QObject *parent) : QObject(parent)
{
    m_sort = new QNetworkAccessManager;
    m_music_url = new QNetworkAccessManager;
    m_music_dowland = new QNetworkAccessManager();
    player = new QMediaPlayer;

    player->setVolume(100);
    connect(m_sort, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotSortFinished(QNetworkReply *)));
    connect(m_music_url, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotGetUrlFinished(QNetworkReply *)));
    connect(m_music_dowland, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotDowlandFinished(QNetworkReply *)));

    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)), this, SLOT(slotPlayStop(QMediaPlayer::State)));

    db = QSqlDatabase::addDatabase("QMYSQL");
    //连接数据库
    db.setHostName("192.168.31.99"); //数据库服务器ip
    db.setUserName("root"); //数据库用户名
    db.setPassword("Z001221z"); //密码
    db.setDatabaseName("mi_meow"); //使用哪个数据库
    //打开数据库
    if( !db.open())
    {
        //数据库打开失败
        qDebug()<<"open database failed";
    }
    getMusicListFromDb();
    //db.close();
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

    song_index = qrand() % sort_result_list.size();
    is_add = false;
}

PetMusic::~PetMusic()
{
    delete player;
}

QString PetMusic::getCurrentMusicInfo()
{
    QString temp = QString("正在播放:%1_%2").arg(song_now.songname)\
            .arg(song_now.fartist);
    return temp;
}

void PetMusic::insertMusicToDb(SONG song)
{
    QSqlQuery query;
    QString sql = QString("insert into music(`songname`,`fartist`,`musicrid`) values('%0','%1','%2');")\
            .arg(song.songname).arg(song.fartist).arg(song.musicrid);
    qDebug()<<sql;
    qDebug()<<query.exec(sql);
    //db.close();

}

void PetMusic::getMusicListFromDb()
{
    QSqlQuery query;
    query.exec("select `songname`,`fartist`,`musicrid` from music");
    while(query.next()) //一行一行遍历
    {
        //取出当前行内容
        SONG temp_song;
        temp_song.fartist = query.value("fartist").toString();
        temp_song.songname = query.value("songname").toString();
        temp_song.musicrid = query.value("musicrid").toString();
        sort_result_list.append(temp_song);
        qDebug()<< query.value(0).toString()
                << query.value("musicrid").toString();

    }
}

void PetMusic::sortMusic(QString text)
{
    //搜索音乐
    QNetworkRequest request;
    text = QString(KUWO_SORT_URL).arg(text);
    qDebug()<<"sort music url:"<<text;
    request.setUrl(QUrl(text));
    m_sort->get(request);
    //sort_result_list.clear();   //清空上一次搜索结果
}


void PetMusic::slotPlayStop(QMediaPlayer::State state)
{
    qDebug()<<state;
    if (is_add)
    {
        is_add = false;
    }
    else if(QMediaPlayer::StoppedState == state)
    {
        qDebug()<<"playstop";

        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
        song_index = qrand() % sort_result_list.size();
        qDebug()<<song_index;
        playMusic();
    }

}

void PetMusic::musicNext()
{
   player->stop();
}

void PetMusic::playMusic()
{
    song_now = sort_result_list.at(song_index) ;    //更新当前正在播放歌曲
    QNetworkRequest request;
    QString text = QString(KUWO_URL_GET).arg(sort_result_list.at(song_index).musicrid);
    qDebug()<<"get play url:"<<text;
    request.setUrl(QUrl(text));
    m_music_url->get(request);
}

void PetMusic::playMusic(SONG song)
{
    song_now = song;    //更新当前正在播放歌曲
    QNetworkRequest request;
    QString text = QString(KUWO_URL_GET).arg(song.musicrid);
    qDebug()<<"get play url:"<<text;
    request.setUrl(QUrl(text));
    m_music_url->get(request);
}

void PetMusic::stopMusic()
{
    player->stop();
}

void PetMusic::analyzeSortResult(QByteArray bytes)
{
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(bytes, &json_error));
    if(json_error.error != QJsonParseError::NoError)
    {
        qDebug() << "json error!"<<json_error.errorString();
        return;
    }
    QJsonObject rootObj = jsonDoc.object();
    QJsonArray absArr = rootObj["abslist"].toArray();
    //for (int i = 0; i < absArr.size(); i++)
    //{
        //将结果存入sort_result,只处理第一个
        QJsonObject temp = absArr.at(0).toObject();
        qDebug()<<"songinfo:";
        qDebug()<<temp[STR_SONGNAME].toString();
        qDebug()<<temp[STR_MUSICRID].toString();
        SONG temp_song;
        temp_song.songname = temp[STR_SONGNAME].toString();
        temp_song.fartist = temp[STR_FARTIST].toString();
        temp_song.musicrid = temp[STR_MUSICRID].toString();
        insertMusicToDb(temp_song);
        sort_result_list.append(temp_song);

        song_index = sort_result_list.size() - 1;
        is_add = true;
        playMusic(sort_result_list.at(song_index));

    //}
    //测试程序，先试着播放搜索结果第一个


}


void PetMusic::slotDowlandFinished(QNetworkReply *reply)
{

}

void PetMusic::slotGetUrlFinished(QNetworkReply *reply)
{
    qDebug()<<"get end";
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        qDebug()<<"play url:"<<bytes;
        player->setMedia(QUrl(bytes));
        qDebug()<<player->currentMedia().canonicalUrl().toString();
        player->play();
    }
    else
    {
        qDebug()<<"error";
        qDebug()<<reply->errorString();
    }
}


void PetMusic::slotSortFinished(QNetworkReply *reply)
{
    //搜所结果
    // 获取响应状态码，200表示正常
    qDebug()<<"end";
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        analyzeSortResult(bytes);
    }
    else
    {
        qDebug()<<"error";
        qDebug()<<reply->errorString();
        // 错误处理-显示错误信息，或显示上一次缓存的图片或叉图。
    }
}

